package com.ruoyi.flow.flow.definition;

import com.ruoyi.flow.flow.workflow.FlowService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import static com.google.common.base.Preconditions.checkArgument;

/**
 * Created by fenghuo on 2018/8/28.
 */
@Service
public class FlowDefinitionService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FlowDefinitionService.class);
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 根据当前任务ID获取流程定义信息
     *
     * @param taskId
     * @return
     */
    @Cacheable("flowCache")
    public ProcessDefinitionEntity getProcessDefinitionByTaskId(String taskId) {
        TaskEntity task = FlowService.taskService().getTaskByTaskId(taskId);
        if (task == null) {
            return null;
        }
        return (ProcessDefinitionEntity) repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
    }

    /**
     * 根据流程定义ID获取流程定义信息
     *
     * @param definitionId
     * @return
     */
    @Cacheable("flowCache")
    public ProcessDefinitionEntity getProcessDefinitionByDefinitionId(String definitionId) {
        checkArgument(StringUtils.isNotEmpty(definitionId), "definitionId must not be null.");
        ProcessDefinition definition = null;
        try {//这里如果流程定义不存在会直接抛出异常，只能捕捉异常
            definition = repositoryService.getProcessDefinition(definitionId);
        } catch (Exception e) {
            LOGGER.error("找不到ID为{}的流程定义", definitionId, e);
        }
        if (definition != null) {
            return (ProcessDefinitionEntity) definition;
        }
        return null;
    }

    /**
     * 根据流程定义标识获取流程定义信息
     *
     * @param definitionKey
     * @return
     */
    @Cacheable("flowCache")
    public ProcessDefinitionEntity getProcessDefinitionByDefinitionKey(String definitionKey) {
        checkArgument(StringUtils.isNotEmpty(definitionKey), "definitionKey must not be null.");
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(definitionKey).singleResult();
        if (definition != null) {
            return (ProcessDefinitionEntity) definition;
        }
        return null;
    }
}
